package com.step.ems.pages.urgent

import com.step.ems.api.ApiService
import com.step.ems.api.UrgentStatus
import com.step.ems.api.req.UrgentReq
import com.step.ems.api.res.UrgentRes
import com.step.ems.common.RefreshType
import com.step.ems.common.UiState
import com.step.ems.common.launch
import com.step.ems.pages.common.PageViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

abstract class UrgentPageViewModel(
    private val apiService: ApiService
) : PageViewModel<UrgentRes>() {
    private var isInit: Boolean = false;

    fun initData() {
        if (!isInit) {
            getData(RefreshType.Init, 100)
            isInit = true
        }
    }

    abstract fun getData(refreshType: RefreshType, delayTime: Long = 0)

    fun getData(refreshType: RefreshType, delayTime: Long = 0, status: UrgentStatus) {
        launch(
            state = _uiState,
            delayTime = delayTime,
            onStart = {
                _uiState.value = UiState.Loading(refreshType)
            }) {
            if (refreshType != RefreshType.LoadMore) pageIndex = 1
            val req = UrgentReq(emergencyStatus = status.value, pageIndex = pageIndex)
            val res = apiService.urgentList(req).get()
            _data.value = when (refreshType) {
                RefreshType.LoadMore -> _data.value + res.records
                else -> res.records
            }
            pageIndex++
            _uiState.value = UiState.Success
        }
    }
}

@HiltViewModel
class UrgentPageAlarmedViewModel @Inject constructor(
    apiService: ApiService
) : UrgentPageViewModel(apiService) {
    override fun getData(refreshType: RefreshType, delayTime: Long) {
        getData(refreshType, delayTime, UrgentStatus.Alarmed)
    }
}

@HiltViewModel
class UrgentPageAcceptViewModel @Inject constructor(
    apiService: ApiService
) : UrgentPageViewModel(apiService) {
    override fun getData(refreshType: RefreshType, delayTime: Long) {
        getData(refreshType, delayTime, UrgentStatus.Accept)
    }
}

@HiltViewModel
class UrgentPageArrowViewModel @Inject constructor(
    apiService: ApiService
) : UrgentPageViewModel(apiService) {
    override fun getData(refreshType: RefreshType, delayTime: Long) {
        getData(refreshType, delayTime, UrgentStatus.Arrow)
    }
}

@HiltViewModel
class UrgentPageCompletedViewModel @Inject constructor(
    apiService: ApiService
) : UrgentPageViewModel(apiService) {
    override fun getData(refreshType: RefreshType, delayTime: Long) {
        getData(refreshType, delayTime, UrgentStatus.Completed)
    }
}

@HiltViewModel
class UrgentPageConfirmedViewModel @Inject constructor(
    apiService: ApiService
) : UrgentPageViewModel(apiService) {
    override fun getData(refreshType: RefreshType, delayTime: Long) {
        getData(refreshType, delayTime, UrgentStatus.Confirmed)
    }
}